from flask import Blueprint, render_template, request
from flask_login import login_required

from app.models.blind_box import BlindBox
from app.models.supermarket import Supermarket
from app.utils.tracking import track_user_behavior

main = Blueprint('main', __name__)

@main.route('/')
@main.route('/index')
@login_required
def index():
    """主页"""
    # 获取盲盒列表
    blind_boxes = BlindBox.query.filter_by(status=1).order_by(BlindBox.create_time.desc()).limit(6).all()
    
    # 获取超市列表
    supermarkets = Supermarket.query.filter_by(status=1).order_by(Supermarket.rating.desc()).limit(6).all()
    
    return render_template('main/index.html', blind_boxes=blind_boxes, supermarkets=supermarkets)

@main.route('/dashboard')
@login_required
def dashboard():
    """管理控制台"""
    # 获取盲盒总数
    total_boxes = BlindBox.query.count()
    
    # 获取超市总数
    total_markets = Supermarket.query.count()
    
    # 获取库存为0的盲盒数量
    out_of_stock = BlindBox.query.filter(BlindBox.stock == 0).count()
    
    # 获取下架的盲盒数量
    inactive_boxes = BlindBox.query.filter(BlindBox.status == 0).count()
    
    stats = {
        'total_boxes': total_boxes,
        'total_markets': total_markets,
        'out_of_stock': out_of_stock,
        'inactive_boxes': inactive_boxes
    }
    
    return render_template('main/dashboard.html', stats=stats)

@main.route('/search')
def search():
    keyword = request.args.get('keyword', '')
    
    # 搜索逻辑...
    
    # 记录搜索行为
    track_user_behavior('search', None, None)
    
    return render_template('main/search_results.html', 
                          results=results, 
                          keyword=keyword) 